﻿function getUrlParam(name) { //获取url 的参数
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return decodeURI(r[2]);
    }
    return null;
}

function postApi(url, data) {

    return new Promise((resolve, reject) => {

        //获取token
        const token = sessionStorage.getItem('token');
        console.log(url)
        console.log(data)
        console.log(token)
        ajax({
            url: url,
            methods: "post",
            data: data,
            timeout: 10000,
            header: {
                //authorization: token,
                // token:token,
                "Content-Type": "application/json"
            },
            success: res => {
                console.log(res);
                resolve(res)
            },
            fail: err => {
                resolve(err)
            },
            complete: () => {

            }
        });

    })
}

function ajax(options) {
    options = options || {}
    // 默认是 GET 请求
    options.methods = options.methods.toUpperCase() || 'GET'
    options.url = options.url || ''
    // 默认是异步请求
    options.async = options.async || true
    options.data = options.data || {}
    options.success = options.success || function () {
    }
    options.faile = options.faile || function () {
    }

    console.log(options)

    let xhr = null

    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest()
    } else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP")
    }

    let params = []
    // 遍历请求参数对象，拼接请求参数
    for (let param in options.data) {
        params.push(param + '=' + options.data[param])
    }
    // 给每个数组后面添加一个 &
    let requestData = params.join('&')
    // 请求类型
    let requestType = options.methods.toUpperCase()
    // 如果是 GET 请求
    if (requestType == 'GET') {
        xhr.open(requestType, options.url + '?' + requestData, options.async)
        xhr.send()
    } else if (requestType == 'POST') { // 如果是 POST 请求
        xhr.open(requestType, options.url, options.async)
        for (let param in Object.keys(options.header)) {
            xhr.setRequestHeader(param, options.data[param]);
        }
        xhr.setRequestHeader("Content-type", "application/json;charset=utf-8");
        xhr.send(JSON.stringify(options.data))

    }

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            options.success(JSON.parse(xhr.responseText))
        } else if (xhr.status != 200) {
            options.faile('request error')
        }
    }
}
